#!/bin/bash
################################################################################
# Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The OpenAirInterface Software Alliance licenses this file to You under 
# the Apache License, Version 2.0  (the "License"); you may not use this file
# except in compliance with the License.  
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#-------------------------------------------------------------------------------
# For more information about the OpenAirInterface (OAI) Software Alliance:
#      contact@openairinterface.org
################################################################################
# file build_epc
# brief
# author Lionel Gauthier
# company Eurecom
# email: lionel.gauthier@eurecom.fr
#
################################
# include helper functions
################################
THIS_SCRIPT_PATH=$(dirname $(readlink -f $0))
source $THIS_SCRIPT_PATH/../BUILD/TOOLS/build_helper

function help()
{
  echo_error " "
  echo_error "Usage: build_epc [OPTION]..."
  echo_error "Build the EPC executable (MME+SP-GW)."
  echo_error " "
  echo_error "Options:"
  echo_error "Mandatory arguments to long options are mandatory for short options too."
  echo_error "  -c, --clean                               Clean the build generated files: config, object, executable files (build from scratch)"
  echo_error "  -C, --conf-files-only                     Generate only EPC configuration files (no build)"
  echo_error "  -D, --daemon                              Build EPC as a daemon."
  echo_error "  -f, --force                               No interactive script for installation of software packages."
  echo_error "  -h, --help                                Print this help."
  echo_error "  -H, --remote-hss                hostname  HSS hostname (with FQDN), default is this host (`hostname --fqdn`)."
  echo_error "  -i, --check-installed-software            Check installed software packages necessary to build and run EPC (support Ubuntu 14.04)."
  echo_error "  -j, --install-gtpu-kernel-module          Install or reinstall specifically the GTPV1-U kernel module (done with -i also) (support Ubuntu 14.04)."
  echo_error "  -t, --install-xtables                     Install or reinstall only xtables without the linux headers."
  echo_error "  -l, --local-hss                           HSS run on the same host."
  echo_error "  -v, --verbose                             Build process verbose."
  echo_error "  -V, --verbose-make                        Make process verbose."
  echo_error "  -x, --clean-certificates                  Clean the EPC certificates"
  echo_error " "
  echo_error "Other options: (you have to know what you are doing)"
  l_realm=`hostname --fqdn`
  l_realm=${l_realm#*.}
  echo_error "  -r, --realm                     realm     Realm of the MME (if not specified, is extracted from this host FQDN ($l_realm))."
  echo_error " "
  echo_error "Examples:"
  echo_error " "
  echo_error "Case 1 - EPC run on same HSS host"
  echo_error "build_epc --local-hss"
  echo_error " "
  echo_error "Case 2 - EPC and HSS do not run on same host"
  echo_error "build_epc --remote-hss my_hss_fqdn"
}

NAME=mme_gwd
DAEMON=/usr/sbin/$NAME
DAEMON_ARGS=""
PIDFILE=/var/run/$NAME.pid


function main()
{
  local -i clean=0
  local -i clean_certificates=0
  local -i conf_files_only=0
  local -i daemon=0
  local -i force=0
  local -i verbose=0
  local -i s6a_server=0
  local -i install_gtpu_kernel_module=0
  local -i install_xtables=0
  local -i var_check_install_oai_software=0
  local    make_args="-j $NUM_CPU"
  local    realm=""
  local    hss_fqdn=""
  local    hss_hostname=""
  local    hss_ip=""
  
  export    cmake_args=" "


  until [ -z "$1" ]
    do
    case "$1" in
      -c | --clean)
        clean=1
        echo "Clean the build generated files (build from scratch)"
        shift;
        ;;
      -C | --conf-files-only)
        conf_files_only=1
        echo "Generate only conf files (no build)"
        shift;
        ;;
      -D | --daemon)
        daemon=1
        cmake_args="$cmake_args -DDAEMONIZE=1"
        echo "Build EPC as a daemon"
        shift;
        ;;
      -f | --force)
        force=1
        echo "Force set (no interactive)"
        shift;
        ;;
      -h | --help)
        help
        shift;
        exit 0
        ;;
      -H | --remote-hss)
        hss_fqdn=$2
        cmake_args="$cmake_args -DHSS_FQDN=$hss_fqdn -DTRANSPORT_option=No_TCP"
        shift 2;
        ;;
      -i | --check-installed-software)
        echo "Check installed software packages necessary to build and run EPC (support Ubuntu 14.04):"
        set_openair_env
        var_check_install_oai_software=1
        shift;
        ;;
      -j | --install-gtpu-kernel-module)
        set_openair_env
        install_gtpu_kernel_module=1
        shift;
        ;;
      -l | --local-hss)
        echo "EPC on same HSS HOST -> MME act as a server on s6a"
        echo "EPC on same HSS HOST -> Diameter use TCP (SCTP disabled), this is the default option."
        s6a_server=1
        cmake_args="$cmake_args -DMME_S6A_IS_SERVER=1 -DTRANSPORT_option=No_SCTP  -DTRANSPORT_PREFER_TCP_option=Prefer_TCP"
        shift 1;
        ;;
      -r | --realm)
        echo "Realm: $2"
        realm=$2
        cmake_args="$cmake_args -DREALM=$realm"
        shift 2;
        ;;
      -t | --install-xtables)
        install_xtables=1
        shift;
        ;;
      -v | --verbose)
        echo "Build process verbose"
        verbose=1
        shift;
        ;;
      -V | --verbose-make)
        echo "Make build process verbose"
        cmake_args="$cmake_args -DCMAKE_VERBOSE_MAKEFILE=ON"
        make_args="VERBOSE=1 $make_args"
        verbose=1
        shift;
        ;;
      -x | --clean-certificates)
        clean_certificates=1
        echo "Clean the MME certificates"
        shift;
        ;;
      *)   
        echo "Unknown option $1"
        help
        exit 1
        ;;
    esac
  done
  
  if [ $install_gtpu_kernel_module -gt 0 ];then
    check_kernel_release_and_install_xtables_addons_oai 3.19.0-28-generic $force
    exit 0
  fi 
  
  if [ $install_xtables -gt 0 ]; then 
    install_xtables_addons_oai $force
    exit 0   
  fi

  if [ $var_check_install_oai_software -gt 0 ];then
    update_package_db
    check_install_mme_gw_software  $force 
    exit 0
  fi
  
  set_openair_env 
  $SUDO cp -uv  $OPENAIRCN_DIR/SCRIPTS/mme_test_s1_pcap2pdml /usr/local/bin
  $SUDO chmod 755 /usr/local/bin/mme_test_s1_pcap2pdml
   
  $SUDO cp -uv  $OPENAIRCN_DIR/SCRIPTS/test_epc              /usr/local/bin
  $SUDO chmod 755 /usr/local/bin/test_epc 
  
  $SUDO mkdir -p -m 755 /usr/share/oai/xsl
  $SUDO cp -upv  $OPENAIRCN_DIR/SRC/TEST/SCENARIOS/play_scenario.xsl    /usr/share/oai/xsl
  $SUDO cp -upv  $OPENAIRCN_DIR/SRC/TEST/SCENARIOS/generic_scenario.xsl /usr/share/oai/xsl
  
  
  # extra arguments processing
  if [[ z$hss_fqdn = z ]]; then
    hss_fqdn=`hostname --fqdn`
    cmake_args="$cmake_args -DHSS_FQDN=$hss_fqdn"
    if [[ z$realm = z ]]; then
      realm=$hss_fqdn
      realm=${realm#*.}
      cmake_args="$cmake_args -DREALM=$realm"
    fi
  else
    if [[ z$realm = z ]]; then
      realm=${hss_fqdn#*.}
      cmake_args="$cmake_args -DREALM=$realm"
    fi
  fi
  hss_hostname=${hss_fqdn%%.*}
  cmake_args="$cmake_args -DHSS_HOSTNAME=$hss_hostname"

  hss_ip=`resolveip --silent $hss_hostname`
  if [[ z$hss_ip = z ]]; then
    hss_ip=`resolveip --silent $hss_fqdn`
  fi
  if [[ z$hss_ip = z ]]; then
    echo_abort "Unable to get HSS IP addr of $hss_fqdn"
  fi
  cmake_args="$cmake_args -DHSS_IP=$hss_ip"

  if [[ $verbose -eq 1 ]]; then
    cecho "OPENAIRCN_DIR    = $OPENAIRCN_DIR" $green
  fi
  
  # for conf files copy in this bash script
  if [ -d /usr/lib/freeDiameter ]; then
    export FREEDIAMETER_PREFIX=/usr
  else
    if [ -d /usr/local/lib/freeDiameter ]; then
      export FREEDIAMETER_PREFIX=/usr/local
    else
      echo_fatal "FreeDiameter prefix not found, install freeDiameter if EPC, HSS"
    fi
  fi
  
  
  
  local dlog=$OPENAIRCN_DIR/BUILD/LOG
  
  mkdir -m 777 -p $dlog
  
  if [ ! -d /usr/local/etc/oai ]; then
    $SUDO mkdir -p -m 777 /usr/local/etc/oai  
  fi
  
  ##############################################################################
  # Clean
  ##############################################################################
  cd $OPENAIRCN_DIR/BUILD/EPC
  if [ $clean -ne 0 ]; then
    if [[ $verbose -eq 1 ]]; then
      echo "Cleaning EPC: generated configuration files, obj files, mme_gw executable"
    fi
    rm -Rf $OPENAIRCN_DIR/BUILD/EPC/BUILD  2>&1
    $SUDO rm -f $FREEDIAMETER_PREFIX/etc/freeDiameter/mme*.conf    2>&1
    $SUDO rm -f $FREEDIAMETER_PREFIX/etc/freeDiameter/epc*.conf    2>&1
    mkdir -m 777 -p -v BUILD
  fi
  if [ $clean_certificates -ne 0 ]; then
    if [[ $verbose -eq 1 ]]; then
      echo "Cleaning EPC: certificates"
    fi
    $SUDO rm -f $FREEDIAMETER_PREFIX/etc/freeDiameter/mme*.pem    2>&1
  fi
  
  ##############################################################################
  # Compile EPC
  ##############################################################################
  cd $OPENAIRCN_DIR/BUILD/EPC
  if [ ! -d ./BUILD ]; then
    mkdir -m 777 -p -v BUILD
  fi
  cmake_file=./CMakeLists.txt
  cp $OPENAIRCN_DIR/BUILD/EPC/CMakeLists.template $cmake_file
  echo 'include(${CMAKE_CURRENT_SOURCE_DIR}/../CMakeLists.txt)' >> $cmake_file
  
  cd ./BUILD
  cmake  $cmake_args .. > /dev/null 
  
  if [ $conf_files_only -eq 0 ]; then
    compilations EPC mme_gw mme_gw $verbose
    if [ $daemon -ne 0 ]; then
      do_stop_daemon
      $SUDO cp -upv $OPENAIRCN_DIR/BUILD/EPC/BUILD/mme_gw /usr/sbin/mme_gwd && echo_success "mme_gwd installed"
    else
      $SUDO killall -q mme_gw
      $SUDO cp -upv $OPENAIRCN_DIR/BUILD/EPC/BUILD/mme_gw /usr/local/bin/ && echo_success "mme_gw installed"
    fi
  fi
  $SUDO cp -upv epc.conf /usr/local/etc/oai
  $SUDO cp -upv mme_fd.conf $FREEDIAMETER_PREFIX/etc/freeDiameter
}


main "$@"


